package com.google.gwt.sample.simplechat.client;

import com.google.gwt.sockets.client.SocketListener;
import com.google.gwt.sockets.client.IOException;
import com.google.gwt.sockets.client.SocketException;

/**
 * Class that handles events from the socket object.
 *
 * @author Aleksey Lagoshin
 */
class SocketHandler implements SocketListener {

  private ChatClient client = ChatClient.getInstance();

  public void onReady() {
    try {
      client.getSocket().connect(client. getHost(), client.getPort());
    }
    catch (SocketException e) {
      client.println(" ** Exception while connecting to the server: " + e.getMessage());
    }
  }

  public void onConnect() {
    client.println(" ** Client has successfully connected to the server");
  }

  public void onCloseConnection() {
    client.println(" ** Server has closed the connection");
  }

  public void onData(int i) {
    try {
      String message = client.getSocket().read();
      if (message != null)
        client.println(" << " + message);
    }
    catch (IOException e) {
      client.println(" ** Input/output exception while reading from socket: " + e.getMessage());
    }
  }

  public void onSecurityError(String message) {
    client.println(" ** Security error: " + message);
  }

  public void onIOError(String message) {
    client.println(" ** Input/output error: " + message);
  }

}
